package com.seo4j.adb4j.gui;

import com.seo4j.adb4j.device.AdbBridgeManager;
import com.seo4j.adb4j.device.exception.DeviceException;
import com.seo4j.adb4j.device.listener.IAndroidDevice;
import com.seo4j.adb4j.gui.panel.ColorPane;
import org.eknet.swing.task.*;
import org.eknet.swing.task.impl.TaskManagerImpl;
import org.eknet.swing.task.ui.TaskBar;
import org.eknet.swing.task.ui.TaskGlassPane;
import org.japura.gui.CheckList;
import org.japura.gui.model.DefaultListCheckModel;
import org.japura.gui.model.ListCheckModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

public class AdbGUI extends javax.swing.JFrame {
    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("com.seo4j.adb4j.gui.messages"); //$NON-NLS-1$
    private JButton buttonRemoveUser;
    private JButton buttonExit;
    private JButton buttonAbout;
    JTable userTable;
    DeviceTableModel deviceTableModel;
    private HashMap<String, DeviceTabPanel> guiMap;
    private ColorPane logPanel;
    private JCheckBox chckbxmntmShowLogs;
    private JButton listDevices;
    private JButton batchUploadBtn;
    private JButton mntmGiveCall;
    private JButton mntmPort;
    CheckList checkList = null;

    ListCheckModel listCheckModel = null;
    public static final Map<String, IAndroidDevice> DEVICE_MAP = new HashMap<String, IAndroidDevice>();
    Task<List<IAndroidDevice>, Long> load_device_task = null;
    final JTabbedPanelWithClose tabbedPanelWithClose = new JTabbedPanelWithClose(JTabbedPane.TOP);

    public AdbGUI() {


        guiMap = new HashMap<String, DeviceTabPanel>();


        initComponents();
        deviceTableModel = new DeviceTableModel();
//        userTable.setModel(deviceTableModel);
//        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//        userTable.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
//        //  userTable.getColumnModel().getColumn(1).setPreferredWidth(100);
//        logPanel.append(Color.blue, "*** ANDRORAT SERVEUR ***\n" +
//                "Authors : A.Bertrand, A.Akimov, R.David, P.Junk\nLaunch at " +
//                (new Date(System.currentTimeMillis())) + "\n" +
//                "On port :  \n");

        //       centrerTable(userTable);
        this.setLocationRelativeTo(null);
        this.setTitle("ADB4J");
        this.setVisible(true);

        load_device_task = new LoadDeviceListTask(this);


        TaskControl<List<IAndroidDevice>> control = taskManager.create(load_device_task);
        control.getContext().addListener(new TaskListener() {
            @Override
            public void stateChanged(ChangeEvent<State> event) {
                log.info(">>> State: " + event.getOldValue() + " => " + event.getNewValue());
                log.info("Started: " + event.getSource().getStartedTimestamp());
            }

            @Override
            public void progressChanged(ChangeEvent<Integer> event) {
                log.info(">>> Progress: " + event.getOldValue() + " => " + event.getNewValue());
            }

            @Override
            public void phaseChanged(ChangeEvent<String> event) {
                log.info(">>> Phase: " + event.getOldValue() + " => " + event.getNewValue());
            }
        });
        control.execute();


//        taskManager.submit(new Runnable() {
//            @Override
//            public void run() {
//
//                for (int k = 0; k < 10; k++) {
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    System.out.println("aaaa" + k);
//                }
//
//            }
//        });


//        log.info("Waited for task: " + value);


    }


    // *******************************
    //	M�thodes du log gui
    // *******************************

    public void logErrTxt(String txt) {
        logPanel.append(Color.red, (new Date(System.currentTimeMillis()) + " " + txt + "\n"));
    }

    public void logTxt(String txt) {
        logPanel.append(Color.black, (new Date(System.currentTimeMillis()) + " " + txt + "\n"));
    }
//
//    public void clientLogTxt(String imei, long date, String txt) {
//        guiMap.get(imei).logTxt(date, txt);
//        //logPanel.append(Color.gray, "Client ("+imei+") at "+(new Date(date))+" : "+txt+"\n");
//    }
//
//    public void clientErrLogTxt(String imei, long date, String txt) {
//        guiMap.get(imei).errLogTxt(date, txt);
//        //logPanel.append(Color.red, "Client ("+imei+") at "+(new Date(date))+" : "+txt+"\n");
//    }


    // *******************************
    //	M�thodes des boutons du menu
    // *******************************

    private void buttonStartActionPerformed() {
        try {
            for (int row = 0; row < userTable.getRowCount(); row++) {
                String imei = (String) deviceTableModel.getValueAt(row, 0);
                if (imei != null) {
                    //server.commandSender(imei, Protocol.DISCONNECT, null);
                }
            }
        } catch (Exception e) {
            //
        } finally {
            this.dispose();
        }
    }

    private void buttonUserGUIActionPerformed() {
        int row = userTable.getSelectedRow();
        if (row != -1) {
            String imei = (String) deviceTableModel.getValueAt(row, 1);

            if (imei != null) {
                DeviceTabPanel gui = guiMap.get(imei);
                if (gui == null) {
                    gui = new DeviceTabPanel(imei, this);
                    guiMap.put(imei, gui);
                } else {
                    gui.setVisible(true);
                }
            }

        } else {
            JOptionPane.showMessageDialog(this, BUNDLE.getString("not-found-content"), BUNDLE.getString("not-found-title"), JOptionPane.ERROR_MESSAGE);
        }
    }

    private void buttonRemoveUserActionPerformed() {
        int row = userTable.getSelectedRow();
        if (row != -1) {
            String imei = (String) deviceTableModel.getValueAt(row, 1);
            if (imei != null) {
                //	server.commandSender(imei, Protocol.DISCONNECT, null);
                this.deleteUser(imei);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No client selected !\nPlease select one client.", "No selection", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void buttonAboutActionPerformed() {
        JOptionPane.showMessageDialog(this, "Adb4j is a free application develop  in Java language.\n" +
                        "Author: seo4j@qq.com\n" +
                        "It is under the GNU GPL3 Licence", "About", JOptionPane.INFORMATION_MESSAGE,
                new ImageIcon(this.getIconImage()));
    }

    private void buttonShowLogs() {
        if (chckbxmntmShowLogs.isSelected()) {
            logPanel.setVisible(true);
            //jScrollPane.setVisible(true);
            //  splitPane.setDividerLocation(0.5);
        } else {
            logPanel.setVisible(false);
            //  jScrollPane.setVisible(false);
            //   splitPane.setDividerLocation(1);
        }
    }


    public class MyRenderer extends DefaultTableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            String country = (String) value;
            ImageIcon getImg;
            //country = "fr";
            File f = new File("src/gui/res/Drapeau/" + country.toUpperCase() + ".png");
            if (f.exists()) {
                getImg = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
                        DeviceTabPanel.class.getResource("/com/seo4j/adb4j/gui/res/Drapeau/" + country.toUpperCase() + ".png")));
            } else {
                getImg = new ImageIcon(Toolkit.getDefaultToolkit().getImage(DeviceTabPanel.class.getResource("/com/seo4j/adb4j/gui/res/Drapeau/default.jpeg")));
            }
            Image img = getImg.getImage();
            Image newimg = img.getScaledInstance(64, 64, java.awt.Image.SCALE_SMOOTH);
            ImageIcon imgResize = new ImageIcon(newimg);
            setIcon(imgResize);
            return this;
        }
    }
    //-------------------------------------------------

    /**
     * Enl�ve de la table des clients, le client mis en param�tre
     *
     * @param imei L'identifiant du client � supprimer
     */
    public void deleteUser(String imei) {
        //    deviceTableModel.removeUser(imei);
        DeviceTabPanel gui = guiMap.get(imei);
        if (gui != null) {
            if (gui.isVisible()) {
                gui.launchMessageDialog("This client is no longer available.\nClosing frame now ...", "Disconnection", JOptionPane.ERROR_MESSAGE);
            }
            //  gui.dispose();
        }
        guiMap.remove(imei);
        getContentPane().repaint();
    }

    /**
     * M�thode appel�e par les UserGUI lors de leur fermeture afin de supprimer la r�f�rence dans la HashMap
     *
     * @param imei L'identifiant de la fenetre
     */
    public void closeUserGUI(String imei) {
        guiMap.remove(imei);
    }


    // *******************************
    //	M�thodes de modif des userGUI
    // *******************************


    public void updatePreference(String imei, String ip, int port, boolean wait, ArrayList<String> phones, ArrayList<String> sms, ArrayList<String> kw) {
        DeviceTabPanel user = guiMap.get(imei);
        user.updatePreference(ip, port, wait, phones, sms, kw);
    }

    public void updateUserMap(String imei, double lon, double lat, double alt, float speed, float accuracy) {
        DeviceTabPanel user = guiMap.get(imei);
        //	user.updateMap(lon, lat, alt, speed, accuracy);
    }

    public void updateUserPicture(String imei, byte[] picture) {
        DeviceTabPanel user = guiMap.get(imei);
        user.updatePicture(picture);
    }

    public void addSoungBytes(String imei, byte[] data) {
        DeviceTabPanel user = guiMap.get(imei);
        //	user.addSoundBytes(data);
    }

    public void addVideoBytes(String imei, byte[] data) {
        DeviceTabPanel user = guiMap.get(imei);
        //	user.addVideoBytes(data);
    }

//    public void updateFileTree(String imei, ArrayList<MyFile> fileList) {
//    	UserGUI user = guiMap.get(imei);
//    	user.updateFileTree(fileList);
//    }
//
//    public void updateUserCallLogs(String imei, ArrayList<CallPacket> logsList) {
//    	UserGUI user = guiMap.get(imei);
//    	user.updateCallLogs(logsList);
//    }

    public void updateContacts(String imei, ArrayList<Contact> contacts) {
        DeviceTabPanel user = guiMap.get(imei);
        //user.updateContacts(contacts);
    }

    public void addMonitoredCall(String imei, int type, String phoneNumber) {
        DeviceTabPanel user = guiMap.get(imei);
        user.addMonitoredCall(type, phoneNumber);
    }

    public void addMonitoredSMS(String imei, String addr, long date, String body) {
        DeviceTabPanel user = guiMap.get(imei);
        user.addMonitoredSMS(addr, date, body);
    }

//    public void updateSMS(String imei, ArrayList<SMSPacket> sms) {
//    	UserGUI user = guiMap.get(imei);
//    	user.updateSMS(sms);
//    }


    // *******************************
    //	M�thodes pour save le channel
    // *******************************


    public void saveMapChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        //	user.saveMapChannel(channel);
    }

    public void saveCallLogChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        user.saveCallLogChannel(channel);
    }

    public void saveContactChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        user.saveContactChannel(channel);
    }

    public void saveMonitorSMSChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        user.saveMonitorSMSChannel(channel);
    }

    public void saveMonitorCallChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        user.saveMonitorCallChannel(channel);
    }

    public void savePictureChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        user.savePictureChannel(channel);
    }

    public void saveSoundChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        // 	user.saveSoundChannel(channel);
    }

    public void saveVideoChannel(String imei, int channel) {
        DeviceTabPanel user = guiMap.get(imei);
        //	user.saveVideoChannel(channel);
    }

    public void saveSMSChannel(String imei, int channel) {
        // TODO
    }

    static TaskManager taskManager = new TaskManagerImpl();

    public static Logger log = LoggerFactory.getLogger(AdbGUI.class);

    // *******************************
    //	M�thodes pour les UserGUI
    // *******************************
    public static void main(String[] args) {


        //  String osarch = System.getProperty("os.arch", "");
        String osname = System.getProperty("os.name", "");
        //  boolean ia64 = osarch.contains("64");


        String adbLocation2 = System.getProperty("com.android.screenshot.bindir");
        System.out.println("bindir:" + adbLocation2);
        //String adbLocation = "E:\\Android\\sdk\\platform-tools\\adb.exe";
        //ProgramFiles : C:\Program Files
        //C:\Program Files (x86)\Xiaomi\MiPhone\Google\Android
        File adbLocation = null;
        String adbHome = System.getenv("ADB_HOME");
        if (adbHome == null || adbHome.trim().isEmpty()) {
            if (osname.startsWith("Windows")) {
                String programFiles = System.getenv("ProgramFiles");
                if (programFiles != null && !programFiles.trim().isEmpty()) {
                    adbHome = programFiles + " (x86)/Xiaomi/MiPhone/Google/Android";
                    adbLocation = new File(adbHome, "adb.exe");
                }
            }
            if (osname.startsWith("Mac")) {
                adbHome = "/Users/seo4j/Library/Android/sdk/platform-tools/";
                adbLocation = new File(adbHome, "adb");
            }
            if (osname.startsWith("Linux")) {
                adbHome = "/home/minios/ext/minios/Android/Sdk/platform-tools/";
                adbLocation = new File(adbHome, "adb");
            }
        } else {
            if (osname.startsWith("Windows")) {
                adbLocation = new File(adbHome, "adb.exe");
            } else {
                adbLocation = new File(adbHome, "adb");
            }
        }

        if (adbLocation != null && adbLocation.canExecute()) {

            System.out.println("adbLocation:" + adbLocation.getAbsolutePath());
            try {
                AdbBridgeManager.init(adbLocation.getAbsolutePath());
            } catch (DeviceException e1) {

            }
//            try {
//                JadbConnection jadb = new JadbConnection();
//                List<JadbDevice> devices = jadb.getDevices();
//                for (JadbDevice d : devices) {
//                    System.out.println(d.getSerial());
//                }
//            }catch (Exception ex){
//
//            }
        }
        if (adbLocation == null) {
            System.out.println(" not found adb ");
            return;
        }

        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        AdbGUI gui = new AdbGUI();


    }


    private void userMouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            this.buttonUserGUIActionPerformed();
        }
    }


    //  static Map<String, Properties> deviceProps = new HashMap<String, Properties>();

    /**
     */
    private void initComponents() {

//    	try {
//    		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }

        BufferedImage image = null;
        try {
            image = ImageIO.read(
                    this.getClass().getResource("/com/seo4j/adb4j/gui/res/androrat_logo_32pix.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.setIconImage(image);

        buttonExit = new JButton();

        buttonRemoveUser = new JButton();


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);


        buttonExit.setText(BUNDLE.getString("ExitApplication")); //$NON-NLS-1$
        buttonExit.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonStartActionPerformed();
            }
        });


        chckbxmntmShowLogs = new JCheckBox(BUNDLE.getString("ShowLogs")); //$NON-NLS-1$
        chckbxmntmShowLogs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                buttonShowLogs();
            }
        });


        chckbxmntmShowLogs.setSelected(true);


        //buttonUserGUI.set(KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK));


        buttonRemoveUser.setText(BUNDLE.getString("DisconnectUser")); //$NON-NLS-1$
        //    buttonRemoveUser.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK));
        buttonRemoveUser.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRemoveUserActionPerformed();
            }
        });


        listDevices = new JButton(BUNDLE.getString("listDevices")); //$NON-NLS-1$
        listDevices.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

//                Task<List<IAndroidDevice>, Long> task = new LoadDeviceListTask();
//
//
//                TaskControl<List<IAndroidDevice>> control = taskManager.create(task);
//                control.execute();


                taskManager.create(load_device_task).execute();
//                TreeMap<String, String> options = new TreeMap<String, String>();
//                options.put("backend", "adb");
//                options.put("adbLocation", adbLocation);
//                ChimpChat chimpChat = ChimpChat.getInstance(options);
//         //       AndroidDebugBridge.init(false);
//                AndroidDebugBridge debugBridge = AndroidDebugBridge.getBridge();
//                IDevice[] devices = debugBridge.getDevices();
//                for (IDevice d : devices) {
//                    System.out.println(d.getSerialNumber());
//                }

//                new Thread(new Runnable() {
//
//                    @Override
//                    public void run() {
//
//
//                    }
//                }).start();


            }
        });
        String UUID_ANDROID = "adb devices|grep -v List|awk '{print $1}'";

        String UUID_IOS = "instruments -s devices|grep -v Devices|cut -d [ -f2|cut -d ] -f1";

        String APP_INFO = "aapt dump badging #apk#";

        String APP_CURRENT_ACTIVITY = "adb -s #udid# shell dumpsys activity";

        String APP_PROCESS_EXISTS = "adb -s #udid# shell ps #package#";

        // api level
        String API_LEVEL = "adb -s #udid# shell getprop ro.build.version.sdk";

        // release version 平台版本号
        String RELEASE_VERSION = "adb -s #udid# shell getprop ro.build.version.release";

        // system version 系统版本号
        String SYS_VERSION = "adb -s #udid# shell getprop ro.build.version.emui";

        // version 版本号
        String VERSION = "adb -s #udid# shell getprop ro.build.display.id";

        // engine version 内核版本号
        String CORE_VERSION = "adb -s #udid# shell cat /proc/version";

        // product 手机型号
        String PRODUCT = "adb -s #udid# shell getprop ro.build.product";

        // resolution 屏幕尺寸
        String RESOLUTION = "adb -s #udid# shell getprop persist.dash.max.rep.resolution";

        // language
        String LANGUAGE = "adb -s #udid# shell getprop persist.sys.language";

        // kill uiautomator 杀死uiautomator进程
        String KILL_APP_PROCESS = "adb -s #udid# shell kill -9 #pid#";

        String KILL_SYS_PROCESS = "kill -9 #pid#";

        // find uiautomator process 查找uiautomator进程
        String FIND_UIAUTOMATOR_PROCESS = "adb -s #udid# shell ps uiautomator";

        // create dir
        String CREATE_DIR = "mkdir -p #dir#";

        // screen capture
        String SCREEN_CAP = "adb -s #udid# shell \"/system/bin/rm /data/local/tmp/screenshot.png;/system/bin/screencap -p /data/local/tmp/screenshot.png\"";

        String SCREEN_IOS_CAP = "idevicescreenshot -u #udid#;mv -f screenshot*.tiff #path2png#";

        // pull screenshot
        String PULL_SCREENSHOT = "adb -s #udid# pull /data/local/tmp/screenshot.png #path2png#";

        // logcat pid
        String LOG_CAT_PID = "adb -s #udid# shell ps logcat|grep logcat";

        // ios syslog pid
        String LOG_SYS_PID = "ps -A|grep idevicesyslog|grep -v grep";

        // logcat command for android
        String LOG_ANDROID_CMD = "adb -s #udid# logcat -v time -b events *:I";

        // syslog command for ios
        String LOG_IOS_CMD = "idevicesyslog -u #udid#";

        // linux date
        String LINUX_DATE = "echo `date +\"%Y%m%d\"`";

        // linux time
        String LINUX_TIME = "echo `date +\"%H%M\"`";

        // windows date
        String WIN_DATE = "echo %DATE:~0,4%%DATE:~5,2%%DATE:~8,2%";

        // windows time
        String WIN_TIME = "echo %TIME:~0,2%%TIME:~3,2%%TIME:~6,2%";
        batchUploadBtn = new JButton(BUNDLE.getString("batchUpload")); //$NON-NLS-1$
        batchUploadBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });


        buttonAbout = new JButton(BUNDLE.getString("About")); //$NON-NLS-1$


        buttonAbout.setText(BUNDLE.getString("AboutAndrorat")); //$NON-NLS-1$
        buttonAbout.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAboutActionPerformed();
            }
        });

//        splitPane = new JSplitPane();
//        splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
//
//        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
//        layout.setHorizontalGroup(
//        	layout.createParallelGroup(Alignment.LEADING)
//        		.addComponent(splitPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 671, Short.MAX_VALUE)
//        );
//        layout.setVerticalGroup(
//        	layout.createParallelGroup(Alignment.LEADING)
//        		.addComponent(splitPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
//        );

//        splitPane.setRightComponent(jScrollPane);


        //  splitPane.setLeftComponent(jScrollPane1);
        //  splitPane.setDividerLocation(200);
//        userTable = new javax.swing.JTable();
//        userTable.setRowMargin(3);
//        userTable.setRowHeight(48);
//        userTable.setFont(new Font("Dialog", Font.PLAIN, 14));
//        userTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
//        userTable.addMouseListener(new MouseAdapter() {
//            @Override
//            public void mouseClicked(MouseEvent e) {
//                userMouseClicked(e);
//            }
//        });


        checkList = new CheckList();

        listCheckModel = new DefaultListCheckModel();

        checkList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {


            }
        });
        checkList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) {
                    IAndroidDevice device = (IAndroidDevice) checkList.getSelectedValue();
                    if (device != null) {
                        DeviceTabPanel userGUI = guiMap.get(device.getSerialNo());
                        if (userGUI == null) {
                            userGUI = new DeviceTabPanel(device.getSerialNo(), AdbGUI.this);
                            guiMap.put(device.getSerialNo(), userGUI);
                        }
                        tabbedPanelWithClose.addTabWithClose(device.getName(), userGUI);
                    }
                }
            }
        });


        checkList.setModel(listCheckModel);
        BorderLayout borderLayout = new BorderLayout();
        getContentPane().setLayout(borderLayout);

        JToolBar bar = new JToolBar();
        bar.setBorderPainted(true);
        bar.setFloatable(false);
        bar.add(listDevices);
        bar.addSeparator();
        bar.add(buttonRemoveUser);
        bar.addSeparator();
        bar.add(batchUploadBtn);
        bar.addSeparator();
        bar.add(chckbxmntmShowLogs);
        bar.addSeparator();
        bar.add(buttonAbout);
        bar.addSeparator();
        bar.add(buttonExit);

        getContentPane().add(bar, BorderLayout.NORTH);


        final JSplitPane splitPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(checkList), tabbedPanelWithClose);
        //   splitPanel.setOneTouchExpandable(true);
        splitPanel.setDividerSize(8);

        splitPanel.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
                splitPanel.setDividerLocation(2.0 / 8.0);
            }
        });
        logPanel = new ColorPane();


        getContentPane().add(splitPanel, BorderLayout.CENTER);
        setGlassPane(new TaskGlassPane(taskManager));

        getContentPane().add(new TaskBar(taskManager), BorderLayout.SOUTH);
        pack();
        //https://github.com/wojujuews/Auto_adb
    }

    private void centrerTable(JTable table) {
        DefaultTableCellRenderer custom = new DefaultTableCellRenderer();
        custom.setHorizontalAlignment(JLabel.CENTER);
        userTable.getColumnModel().getColumn(0).setPreferredWidth(56);
        for (int i = 1; i < table.getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setCellRenderer(custom);
        }
    }
}
